package com.itheima.reggie.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@Slf4j
public class DishController {

    private Integer count = 0;

    @Autowired
    private DishService dishService;


    @Autowired
    private RedisTemplate redisTemplate;

    //查询指定分类下菜品
    @GetMapping("/dish/list")
    public ResultInfo findList(Long categoryId, Integer status) {

        //设置Redis的键
        String key = "dish_" + categoryId;

        //在Redis中查找
        ValueOperations valueOperations = redisTemplate.opsForValue();
        List<Dish> dishList = (List<Dish>) valueOperations.get(key);

        //找到直接返回
        if (CollectionUtil.isNotEmpty(dishList)) {

            log.info("第" + count + "次在Redis中找到了数据");
            count++;
            return ResultInfo.success(dishList);
        }

        //没找到在Redis中存储一份，然后返回给前端
        dishList = dishService.findList(categoryId, null);
        valueOperations.set(key, dishList);
        return ResultInfo.success(dishList);
    }
}
